package cs2340.g21.wms;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.LinkedList;
import java.util.List;

import android.os.Bundle;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.content.Intent;
import android.support.v4.app.DialogFragment;
import android.support.v4.app.FragmentActivity;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.DatePicker;
import android.widget.EditText;

public class SearchActivity extends FragmentActivity {
	
    private static final String LOG_TAG = "DEBUGGER";
    private Coordinator coordinator;
    
    //ui elements
    private EditText searchText;
    private EditText searchDescription;
    private EditText searchTags;

    //
    private Category mCategory = Category.LOST;
    private String mName;
    private String mDescription;
    private List<String> mTags = new LinkedList<String>();
    private List<Item> searchList;
    
    //Date and datepicker
    private Calendar calendar = Calendar.getInstance();
    private int startDay = 0;
    private int startMonth = 0; 
    private int startYear = 0; 
    private int endDay = 0;
    private int endMonth = 0;
    private int endYear = 0;
    private EditText startText, endText;
    private int currentPicker;
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        coordinator = new Coordinator();
        if(getIntent().getExtras() != null){
            coordinator = (Coordinator) getIntent().getExtras().getSerializable("cs2340.g21.wms.coordinator");
        }
        setContentView(R.layout.activity_search);
        searchText = (EditText) findViewById(R.id.searchText);
        searchDescription = (EditText) findViewById(R.id.searchDescription);
        searchTags = (EditText) findViewById(R.id.searchTags);
        searchList = new ArrayList<Item>();
        populateStartDate(0, -1, 0);
        populateEndDate(0, -1, 0);
    }
    
    

    public void updateCategory(View view) {
        switch (view.getId()) {
            case R.id.flost_radio:
                mCategory = Category.LOST;
                break;
            case R.id.ffound_radio:
                mCategory = Category.FOUND;
                break;
            case R.id.fdonation_radio:
                mCategory = Category.DONATE;
                break;
            case R.id.fall_radio:
            	mCategory = Category.ALL;
            	break;
        }
        
        
    }
    
    public void setStartDate(View view){
        DialogFragment startFrag = new DatePickerFragment();
        currentPicker = 0;
        startFrag.show(getSupportFragmentManager(), "datePicker");
    }
    
    public void setEndDate(View view){
        DialogFragment endFrag = new DatePickerFragment();
        currentPicker = 1;
        endFrag.show(getSupportFragmentManager(), "datePicker");
    }
    
    public void populateStartDate(int day, int month, int year){
        startText = (EditText)findViewById(R.id.startDateText);
        startText.setText(day+"."+(month+1)+"."+year);
    }
    
    public void populateEndDate(int day, int month, int year){
        endText = (EditText)findViewById(R.id.endDateText);
        endText.setText(day+"."+(month+1)+"."+year);
    }
    
    public void confirm(View view){
        mName = searchText.getText().toString();
        mDescription = searchDescription.getText().toString();
    	addToTags(searchTags.getText().toString());
        Filter filter = new Filter(coordinator.getItems());
        if(mCategory == Category.ALL){
        	searchList = (ArrayList<Item>) coordinator.getItems();
        }else if(mCategory == Category.LOST){
            //Log.d(LOG_TAG, "filter lost");
            searchList = (ArrayList<Item>)filter.lostFilter();
        }else if(mCategory == Category.FOUND){
            //Log.d(LOG_TAG, "filter found");
            searchList = (ArrayList<Item>)filter.foundFilter();
        }else if(mCategory == Category.DONATE){
            //Log.d(LOG_TAG, "filter donate");
            searchList = (ArrayList<Item>)filter.donateFilter();
        }
        filter.setItems(searchList);
        
        if(!mName.equals("")){
        	for(Item i : searchList){
        		if(!i.getName().toLowerCase().equals(mName.toLowerCase())){
        			searchList.remove(i);
        		}

        		if(!i.getName().toLowerCase().equals(mName.toLowerCase())){
        			Log.d("DEBUGER", "removed");
        			searchList.remove(i);
        		}
            
        	}
        }
        if(!mDescription.equals("")){
        	for(Item i : searchList){
        		if(!i.getDescription().toLowerCase().equals(mDescription.toLowerCase())){
        			searchList.remove(i);
        		}
        	}
        }
        if(!mTags.equals("")){
        	for(Item i : searchList){
        		for(String t : mTags){
        			if(i.getTags().contains(t)){
        				searchList.remove(i);
        			}
        		}
        	}
        }
        
        Intent intent = getIntent();
        intent.putExtra("original", (ArrayList<Item>)searchList);
        intent.putExtra("items", (ArrayList<Item>)searchList);
        intent.putExtra("coordinator", coordinator);
        intent.setClass(SearchActivity.this, ItemListActivity.class);
        finish();
        startActivity(intent);
    }
    
    /**
     * populates mTags with the user's searched tags
     * @param tags string of tags taken from user input
     */
    private void addToTags(String tags) {
    	if (tags != null) {
	    	String newTags = "";
			for (int i=0; i<tags.length(); i++) {
				if (tags.charAt(i) != '#') {
					newTags += tags.charAt(i);
				}
			}
			String[] tagArray = newTags.split(",");
			for(String item:tagArray) {
				if (item.length() != 0) {
					mTags.add(item.trim());
				}
			}
    	}
    	mTags.add(mName);
    }
    
    public void cancel(View view){
        Intent intent = getIntent();
        intent.putExtra("cs2340.g21.wms.coordinator", coordinator);
        intent.setClass(SearchActivity.this, HomeScreenActivity.class);
        finish();
        startActivity(intent);
    }
    
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.activity_search, menu);
        return true;
    }
    
    
    /**
     * Datepicker used to set the start and end dates of the search. Knows which picker is 
     * being used through the value of currentPicker
     */
	private class DatePickerFragment extends DialogFragment implements DatePickerDialog.OnDateSetListener{
        boolean fired = false;
        public Dialog onCreateDialog(Bundle savedInstanceState){
            int year = calendar.get(Calendar.YEAR);
            int month = calendar.get(Calendar.MONTH);
            int day = calendar.get(Calendar.DAY_OF_MONTH);
            
            return new DatePickerDialog(getActivity(), this, year, month, day);
        }
        @Override
        public void onDateSet(DatePicker view, int year, int monthOfYear,
                int dayOfMonth) {
            if(!fired){ //there is a bug that fires these twice for some reason, this avoids
                if(currentPicker == 0){
                    Log.d(LOG_TAG, currentPicker + "lel");
                    startDay = dayOfMonth;
                    startMonth = monthOfYear;
                    startYear = year;
                    populateStartDate(startDay, startMonth, startYear);
                }
                if(currentPicker == 1){
                    Log.d(LOG_TAG, currentPicker + "lol");
                    endDay = dayOfMonth;
                    endMonth = monthOfYear;
                    endYear = year;
                    populateEndDate(endDay, endMonth, endYear);
                }
                fired = true;
            }
        }
    }
	
    @Override
    public void onBackPressed() {
        Intent intent = new Intent();
        intent.putExtra("cs2340.g21.wms.coordinator", coordinator);
        intent.setClass(SearchActivity.this, HomeScreenActivity.class);
        startActivity(intent);
        finish();
    }

}
